<?php

namespace App\Services;

use App\Models\CompanyUser;
use App\Models\Menu;
use App\Models\Role;
use App\Models\User;
use Illuminate\Database\Eloquent\Model;

/**
 * Class RoleService 角色服务类
 * @package App\Services
 */
class RoleService extends BaseService
{
    /**
     * 创建角色
     */
    public function saveData($params)
    {
        $menuIds = '';
        if (!empty($params['permissions'])) {
            $menuIds = to_array($params['permissions']);
            sort($menuIds); //排序，让menu_id从小到大
            $menuIds = implode(',', $menuIds);
        }
        if ($params['id']) {
            $role = Role::query()->find($params['id']);
            CommonService::addActionLog("修改角色", "把{$role->title}修改为{$params['title']}");
        } else {
            $role = new Role();
            CommonService::addActionLog("添加角色：{$params['title']}");
        }
        $role->title      = $params['title'];
        $role->creator_id = user_id();
        $role->menu_ids   = $menuIds;
        $role->company_id = company_id();
        $role->status     = $params['status'];
        $role->save();

        return $role->id;
    }

    /**
     *  获取一条角色记录信息
     */
    public function getInfo($id)
    {
        $role = Role::query()->where('id', $id)
            ->select('id', 'title', 'menu_ids', 'company_id', 'status')
            ->first();

        if(!$role) return [];

        $role = $role->toArray();
        $menuIds = explode(',', $role['menu_ids']);
        unset($role['menu_ids']); //前端用不到，去掉

        $list = Menu::query()
            ->whereIn('id', $menuIds)
            ->select('id', 'title', 'parent_id')
            ->get()
            ->toArray();

        $role['userAuthMenus'] = (new RuleMenuService())->leftMenus();
        $role['rules'] = (new RuleMenuService())->getTree($list);

        return $role;
    }

    /**
     * 获取角色列表
     * 如果是超管，可以看到公司管理员权限
     * 如果公司公司管理员，那看到的只是本公司的角色（），不包括自己的管理员角色
     */
    public function getList($params, $perPage)
    {
        $companyId = company_id();
        $thisQuery = Role::query()->where('company_id', $companyId);
        if (isset($params['keyword']) && !empty($params['keyword'])) {
            $keyword = $params['keyword'];
            $thisQuery->where('title', 'like', "%{$keyword}%");
        }
        $list = $thisQuery->get();
        if ($list->isEmpty()) return [];
        $list = $list->toArray();
        foreach ($list as &$val) {
            $userIds = CompanyUser::query()
                ->where('role_id', $val['id'])
                ->pluck('user_id')
                ->toArray();
            $val['users'] = User::query()->whereIn('id', $userIds)->select('id', 'nickname')->get()->toArray();
            $val['menus'] = Menu::query()
                ->whereIn('id', to_array($val['menu_ids']))
                ->where('parent_id', 0)
                ->where('is_menu', 1)
                ->select('id', 'title')
                ->get()
                ->toArray();
            $val['is_edit'] = ($val['title'] == '公司管理员') ? 0 : 1;
        }

        return $this->removeNoUsedPageParams($list);
    }

    /**
     * 修改角色
     */
    public function updateData($params, $id)
    {
        $role = Role::query()->find($id);
        $menuIds = '';
        if (!empty($params['permissions'])) {
            $menuIds = to_array($params['permissions']);
            sort($menuIds); //排序，让menu_id从小到大
            $menuIds = implode(',', $menuIds);
        }
        $role->title = $params['title'];
        $role->menu_ids = $menuIds;
        $role->status = $params['status'];
        if (!$role->save()) {
            return false;
        }
        CommonService::addActionLog("修改角色", "把{$role->title}修改为{$params['title']}");
        return true;
    }

    /**
     * 角色启用禁用
     */
    public function changeStatus($id, $status)
    {
        $role = Role::query()->find($id);
        if (!$role) return false;
        $role->status = $status;

        $status = $status ? '启用' : '禁用';
        CommonService::addActionLog("角色启用禁用", "把 {$role->title} 改为$status");

        return $role->save();
    }

    /**
     * 获取软删除的数据列表(回收站数据)
     */
    public function getRecycles($request): array
    {
        $thisQuery = Role::onlyTrashed();

        if ($request->filled('keyword')) { //判断参数是否存在并且不为空
            $keyword = $request->input('keyword');
            $thisQuery->where('title', 'like', "%{$keyword}%")->orWhere('id', '=', $keyword); //由于不同的表字段不同，所以单独拿出来
        }

        return $this->formatRecycleData($request, $thisQuery);
    }


}
